package model

import (
	"common/helper"
	myredis "common/redis"
	myUserHelp "common/userHelp"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	mrand "math/rand"
	ryrpc "member/rpc"
	"time"
)

type TurntableInfo struct {
	Reward float64 `json:"reward"` //转盘奖励金额
	Count  int     `json:"count"`  //转盘奖励次数
	Type   int     `json:"type"`   //1 大随机金额 2 小随机金额 3 1000元 4 50元 5 1元 6 获得随机次数 7 直接领奖 8 无奖励 9 后台增加
	Remark string  `json:"remark"`
}

func TurnTableClick(uid string) (TurntableInfo, error) {
	var turntableInfo TurntableInfo
	//查询后台转盘开关是否开启
	if !TurntableSwitch() {
		return turntableInfo, nil
	}

	info, err := myUserHelp.GetPddTurntableInfo(uid)
	if !err {
		return turntableInfo, errors.New(helper.UIDErr)
	}
	//验证活动是否停止
	if info.Enabled == 0 {
		return turntableInfo, errors.New(helper.PromoClosed)
	}
	//验证是否有抽奖次数
	if info.UnuseChance < 1 {
		return turntableInfo, errors.New(helper.TurnTableTimesErr)
	}
	//判断是否第一次抽奖
	var firstTime bool
	if info.UsedChance == 0 {
		firstTime = true
	}

	turntableInfo = SpinWheel(firstTime)

	// 新增转盘记录明细
	totAmount := info.Amount + info.HandAmount
	balAfter := totAmount + turntableInfo.Reward
	history := ryrpc.TblPddTurntableHistory{
		Id:           helper.GenId(),
		Uid:          uid,
		Amount:       turntableInfo.Reward,
		BeforeAmount: totAmount,
		AfterAmount:  balAfter,
		CreatedAt:    time.Now().Unix(),
		Type:         turntableInfo.Type,
		Remark:       turntableInfo.Remark,
	}

	query, _, _ := dialect.Insert("tbl_pdd_turntable_history").Rows(history).ToSQL()
	myredis.AddLogToRedis(query)

	myUserHelp.G_UserPdd.AddUnuseChance(uid, -1)
	myUserHelp.G_UserPdd.AddUseChance(uid, 1)
	myUserHelp.G_UserPdd.AddAmount(uid, turntableInfo.Reward)
	myUserHelp.G_UserPdd.SetUpdatedAt(uid, time.Now().Unix())

	return turntableInfo, nil
}

func Apply(param ApplyParam) error {
	//查询后台转盘开关是否开启
	if TurntableSwitch() {
		var data []ryrpc.TblPddTurntableReview
		query, _, _ := dialect.From("tbl_pdd_turntable_review").Select(colsTurntableReview...).Where(g.Ex{"uid": param.Uid}).ToSQL()
		err := meta.MerchantDB.Select(&data, query)
		if err != nil {
			return errors.New(helper.DBErr)
		}
		if len(data) > 0 {
			for _, i := range data {
				// 已经有审核状态的不能再提交
				if i.State == 1 {
					return errors.New(helper.DuplicateApplyErr)
				}
			}
		}
		res, ret := myUserHelp.GetPddTurntableInfo(param.Uid)
		if !ret {
			return errors.New(helper.UIDErr)
		}

		if (res.Amount + res.HandAmount) < 100 {
			return errors.New(helper.RewardAmountUnreached)
		}

		// 写入转盘审核记录
		review := ryrpc.TblPddTurntableReview{
			Id:       helper.GenId(),
			Uid:      param.Uid,
			Username: param.Username,
			Amount:   param.Amount,
			State:    1,
			ApplyAt:  time.Now().Unix(),
		}

		query, _, _ = dialect.Insert("tbl_pdd_turntable_review").Rows(review).ToSQL()
		myredis.AddLogToRedis(query)
	}
	return nil
}

func SpinWheel(firstTime bool) TurntableInfo {
	var res TurntableInfo
	if firstTime {
		res.Reward = mrand.Float64()*3 + 93 // 随机获得93-96元
		res.Type = 1
		res.Remark = "大随机金额"
		firstTime = false
		return res
	}

	chance := mrand.Float64()
	if chance < 0.0005 {
		res.Count = mrand.Intn(3) + 1
		res.Type = 6
		res.Remark = fmt.Sprintf("获得%d次随机次数", res.Count)
	} else if chance < 0.4005 {
		a := mrand.Float64()
		res.Reward = a*0.59 + 0.01 // 获得0.01-0.6元的金额
		res.Type = 2
		res.Remark = "小随机金额"
	} else {
		res.Reward = 0
		res.Type = 8
		res.Remark = "无奖励"
	}
	return res
}
